package com.hubu.blog.handler;

import com.hubu.blog.entity.response.Result;
import com.hubu.blog.entity.response.error.ErrorResult;
import com.hubu.blog.exception.BusinessException;
import com.hubu.blog.exception.GlobalException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public Result<ErrorResult> handleBusinessException(BusinessException e, WebRequest request) {
        ErrorResult errorDetail = ErrorResult.builder()
                .path(request.getDescription(false).replace("uri=", ""))
                .errorType(e.getClass().getSimpleName())
                .build();

        return Result.<ErrorResult>builder()
                .code(e.getCode())
                .message(e.getMessage())
                .data(errorDetail)
                .build();
    }

    @ExceptionHandler(GlobalException.class)
    public Result<ErrorResult> handleGlobalException(GlobalException e, WebRequest request) {
        ErrorResult errorResult = ErrorResult.builder()
                .path(request.getDescription(false).replace("uri=", ""))
                .errorType(e.getClass().getSimpleName())
                .build();

        return Result.<ErrorResult>builder()
                .code(500)
                .message(e.getMessage())
                .data(errorResult)
                .build();
    }
}